/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExibeLigacoes.java
 *
 * Created on 02/08/2010, 15:45:45
 */
package user_gui;

import in_out.GeraRelatorio;
import java.io.File;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import op.EntradaAbstrata;
import op.Ligacao;

/**
 *
 * @author Jônatas
 */
public class ExibeLigacoes extends javax.swing.JFrame {

    private List<Ligacao> ligacoes;

    public ExibeLigacoes(List<Ligacao> ligacoes) {
        this.ligacoes = ligacoes;
        initComponents();
        fillTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ligações");
        setResizable(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Origem", "Destino", "Data", "Hora", "Duração", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Cria Relatório");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 404, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-577)/2, (screenSize.height-493)/2, 577, 493);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileFilter() {

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                }

                return f.getName().endsWith(".xls");
            }

            @Override
            public String getDescription() {
                return "*.xls";
            }
        });

        chooser.showSaveDialog(this);
        File file = chooser.getSelectedFile();

        if (file.exists()) {

            String[] options = {"Sim", "Não"};

            int ctz = JOptionPane.showOptionDialog(this, "Deseja sobrescrever o arquivo existente?", "Aviso",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

            if (ctz != 0) {
                return;
            }

        }

        String filePath = file.getAbsolutePath();
        if (!filePath.endsWith(".xls")) {
            filePath += ".xls";
        }

        String[] titulo = new String[6];

        for (int i = 0; i < titulo.length; i++) {
            titulo[i] = jTable1.getColumnName(i);
        }

        String[][] tabela = new String[jTable1.getRowCount()][6];

        for (int i = 0; i < jTable1.getRowCount(); i++) {

            tabela[i][0] = jTable1.getValueAt(i, 0).toString();
            tabela[i][1] = jTable1.getValueAt(i, 1).toString();
            tabela[i][2] = jTable1.getValueAt(i, 2).toString();
            tabela[i][3] = jTable1.getValueAt(i, 3).toString();
            tabela[i][4] = jTable1.getValueAt(i, 4).toString();
            tabela[i][5] = jTable1.getValueAt(i, 5).toString();
        }

        try {
            GeraRelatorio.createSimpleReport(titulo, tabela, new File(filePath), "Relatório");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Houve um problema na escrita do arquivo, por favor verifique se este"
                    + "arquivo não está sendo utilizado por outra aplicação.", "Erro", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JOptionPane.showMessageDialog(this, "O arquivo foi salvo com sucesso", "", JOptionPane.INFORMATION_MESSAGE);

    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables

    private void fillTable() {

        String[][] tabela = new String[ligacoes.size()][6];

        for (int i = 0; i < tabela.length; i++) {

            tabela[i][0] = ligacoes.get(i).getNumeroDeOrigem().toString();
            tabela[i][1] = ligacoes.get(i).getDestino().toString();

            String data = pegaData(ligacoes.get(i).getDataOrigemLigacao());
            String hora = pegaHora(ligacoes.get(i).getDataOrigemLigacao());

            tabela[i][2] = data;
            tabela[i][3] = hora;

            String duracao = EntradaAbstrata.getDuracaoHoras(ligacoes.get(i).getDuracao().intValue());

            tabela[i][4] = duracao;

            NumberFormat nf = NumberFormat.getCurrencyInstance();

            tabela[i][5] = nf.format(ligacoes.get(i).getCusto().doubleValue());

        }

        jTable1.setModel(new DefaultTableModel(tabela, new String[]{
                    "Origem", "Destino", "Data", "Hora", "Duração", "Valor"
                }) {

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        });

    }

    private String pegaData(Date dataOrigemLigacao) {

        Calendar cal = Calendar.getInstance();
        cal.setTime(dataOrigemLigacao);

        String resp = cal.get(Calendar.DATE) + "/";
        resp += (cal.get(Calendar.MONTH)+1) + "/";
        resp += cal.get(Calendar.YEAR);

        return resp;

    }

    private String pegaHora(Date dataOrigemLigacao) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dataOrigemLigacao);

        String hora = "" + cal.get(Calendar.HOUR_OF_DAY);

        if (hora.length() == 1) {
            hora = "0" + hora;
        }

        String min = "" + cal.get(Calendar.MINUTE);
        if (min.length() == 1) {
            min = "0" + min;
        }

        String seg = "" + cal.get(Calendar.SECOND);
        if (seg.length() == 1) {
            seg = "0" + seg;
        }

        String resp = hora + ":";
        resp += min + ":";
        resp += seg;

        return resp;
    }
}
